package com.example.boot.modules.system.controller;


import com.example.boot.modules.system.constant.PM;
import com.example.boot.modules.system.convert.ClientConvert;
import com.example.boot.modules.system.dto.ClientDto;
import com.example.boot.modules.system.entity.Client;
import com.example.boot.modules.system.service.IClientService;
import com.example.boot.modules.system.vo.ClientVo;
import com.example.starter.util.Response;
import com.example.starter.webmvc.valid.CreateValid;
import com.example.starter.webmvc.valid.UpdateValid;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;


/**
 * @author 王令
 * @since 2023-02-15
 */
@RequiredArgsConstructor
@RestController
@RequestMapping("/system/client")
public class ClientController {

    private final IClientService service;

    @PreAuthorize("hasAuthority('" + PM.CLIENT_WRITE + "')")
    @PostMapping
    public Response<Boolean> create(@RequestBody @Validated(CreateValid.class) ClientDto clientDto) {
        Client client = ClientConvert.INSTANCE.toClientDto(clientDto);
        service.create(client);
        return Response.ok();
    }

    @PreAuthorize("hasAuthority('" + PM.CLIENT_WRITE + "')")
    @PutMapping
    public Response<Boolean> update(@RequestBody @Validated(UpdateValid.class) ClientDto clientDto) {
        Client client = ClientConvert.INSTANCE.toClientDto(clientDto);
        service.update(client);
        return Response.ok();
    }

    @PreAuthorize("hasAuthority('" + PM.CLIENT_WRITE + "')")
    @DeleteMapping("/{id}")
    public Response<Boolean> deleteById(@PathVariable("id") String id) {
        service.removeById(id);
        return Response.ok();
    }

    @PreAuthorize("hasAuthority('" + PM.CLIENT_READ + "')")
    @GetMapping("/{id}")
    public Response<ClientVo> findById(@PathVariable("id") String id) {
        Client client = service.getById(id);
        return Response.ok(ClientConvert.INSTANCE.toClientVo(client));
    }

    @PreAuthorize("hasAuthority('" + PM.CLIENT_READ + "')")
    @GetMapping("/list")
    public Response<List<ClientVo>> listAll() {
        List<Client> clients = service.list();
        return Response.ok(ClientConvert.INSTANCE.toClientVoList(clients));
    }
}
